<template>
  <div class="container">
    <div class="background-image"></div>
    <div class="content">
     
      <div class="view-profile">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-row :gutter="20">
              <el-col :span="4">
                <el-row>
                  <el-col :span="24">
                    <el-button style="width: 100%;;" type="primary" @click="addArt()"><i class="el-icon-thumb" ></i> 发 布 帖 子</el-button>

                  </el-col>
                  <el-col :span="24">
                    <el-button style="width: 100%;margin-top: 10px;" type="success" @click="fetchPets()"><i class="el-icon-user"></i> 所 有 帖 子</el-button>

                  </el-col>
                  <el-col :span="24">
                    <el-button style="width: 100%;margin-top: 10px;" type="warning" @click="myArt()"><i class="el-icon-user"></i> 我 的 帖 子</el-button>

                  </el-col>
                  <el-col :span="24">
                    <el-input style="margin-top: 10px;" prefix-icon="el-icon-search" placeholder="搜索帖子 输入标题" v-model="soushuo">
                      <el-button slot="append" icon="el-icon-search"  @click="search()"></el-button>
                    </el-input>
                  </el-col>
                </el-row>
                


              </el-col>
              <el-col :span="20">
                <el-row :gutter="20">
                  <el-col :span="8" v-for="item in articles">
                  <el-card :body-style="{ padding: '20px' }" class="pet-card hvr-float">
                    <div @click="JumpArticle(item)">
                      <span style="font-size: 20px;font-weight: 600;">{{ item.title }}</span>
                      <p style="font-size: 14px; color: #8a919f; height: 60px; overflow: hidden;text-overflow: ellipsis;"><strong style="color: black;">文章简介</strong> <span >{{ item.summary }}</span></p>
                      <p style="color: #8a919f;font-size: 14px;"><strong>作者</strong> {{ item.createBy }}</p>
                      <p style="color: #8a919f;font-size: 14px;"><strong>发布时间</strong> {{  formatDate(item.createTime)}}</p>
                    </div>
                    <div class="button-container">
                      <el-button class="custom-button" type="danger" @click="deletePet(item.id)"  v-if="item.authId == userId">删除</el-button>
                      <el-button class="custom-button" type="primary" @click="editPet(item)"  v-if="item.authId == userId">编辑</el-button>
                    </div>
                  </el-card>
                </el-col>
                </el-row>
              </el-col>
            </el-row>

          </el-col>
          
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import jwtDecode from 'jwt-decode';

export default {
  name: 'ArticleView',
  data() {
    return {
      articles: [],
      userId: null,
      soushuo:null
    };
  },
  created() {
    this.userId = this.getUserIdFromToken();
    this.fetchPets();
  },
  methods: {
    getUserIdFromToken() {
      const token = localStorage.getItem('token');
      if (token) {
        const decoded = jwtDecode(token);
        console.log("Decoded token:", decoded);
        const userId = decoded.userId;
        console.log("Parsed userId from token:", userId);
        return userId; // 确保 JWT 中有 userId 字段
      }
      return null;
    },
    fetchPets() {
      if (this.userId) {
        console.log(`Fetching pets for userId: ${this.userId}`);

        axios.get('/api/article/list', {
          headers: {'Authorization': `Bearer ${localStorage.getItem('token')}`},
        })
        .then(response => {
          console.log("Pets data received:", response.data);
          this.articles = response.data;
          
        })
        .catch(error => {
          console.error("获取帖子信息失败:", error);
        });
      } else {
        console.error("未能获取用户ID");
      }
    },
    formatDate(date) {
      if (date) {
        const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
        return new Date(date).toLocaleDateString(undefined, options);
      }
      return '';
    },
    deletePet(id) {
      axios.delete(`/api/article/${id}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      .then(response => {
        this.$message.success('帖子已删除');
        this.fetchPets(); // 重新获取宠物列表
      })
      .catch(error => {
        this.$message.error('删除失败，请重试');
        console.error("删除帖子失败:", error);
      });
    },
    editPet(item) {
      this.$router.push({
        path: '/createArticle',
        query: { id: item.id }
      });
    },
    chatWithPet(petId) {
      this.$router.push({
        path: '/chat',
        query: { petId: petId }
      });
    },
    viewDiary(petId) {
      this.$router.push({
        path: '/diary',
        query: { petId: petId }
      });
    },

    


    JumpArticle(item){
       
        this.$router.push({ path: "/articleIndex" ,query: { articleId: item.id}});
    },


    addArt(){
      console.log('okok')
      this.$router.push({ path: "/createArticle"});
    },

    myArt(){
      axios.get('/api/article/list', {
          headers: {'Authorization': `Bearer ${localStorage.getItem('token')}`},
          params: { authId: this.userId }
        })
        .then(response => {
          console.log("Pets data received:", response.data);
          this.articles = response.data;
          
        })
        .catch(error => {
          console.error("获取帖子信息失败:", error);
        });
    },


    search(){
      axios.get('/api/article/list', {
          headers: {'Authorization': `Bearer ${localStorage.getItem('token')}`},
          params: { title: this.soushuo }
        })
        .then(response => {
          console.log("Pets data received:", response.data);
          this.articles = response.data;
          
        })
        .catch(error => {
          console.error("获取帖子信息失败:", error);
        });
    },

  }
};
</script>

<style scoped>
.container {
  position: relative;
  width: 100%;
  min-height: 100vh; /* 确保容器高度随内容变化 */
  display: flex;
  justify-content: center;
  align-items: flex-start; /* 使内容从顶部开始对齐 */
  background-color: #000; /* 备用背景颜色 */
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/background.jpg'); /* 使用相对路径引入图片 */
  background-size: cover; /* 确保背景图片覆盖整个容器 */
  background-repeat: no-repeat;
  background-attachment: fixed; /* 背景图片随页面滚动 */
  background-position: center;
  opacity: 0.8; /* 根据需要调整透明度 */
}

.content {
  position: relative;
  z-index: 1;
  width: 100%;
  padding: 20px;
}

.view-profile {
  margin: 20px;
}

.pet-card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.9); /* 设置背景颜色和透明度 */
  border-radius: 8px; /* 设置圆角 */
}

.button-container {
  height: 25px;
  display: flex;
  flex-wrap: nowrap; /* 禁止换行 */
  justify-content: start; /* 按钮均匀分布 */
  margin-top: 10px;
}

.custom-button {
  flex: 1; /* 按钮均分父容器空间 */
  margin: 0 1px; /* 按钮之间的间距 */
  min-width: 50px; /* 设置按钮最小宽度 */
  max-width: 50px; /* 设置按钮最大宽度 */
  padding: 4px 0; /* 设置按钮的上下内边距 */
  text-align: center; /* 文字居中 */
}

.hvr-float:hover, .hvr-float:focus, .hvr-float:active {
  -webkit-transform: translateY(-3px);
  transform: translateY(-3px);
  color: #409EFF;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
</style>
